package ai.mspbots.poc.interceptor;

import ai.mspbots.poc.help.WordVectorsThreadLocal;
import org.deeplearning4j.models.embeddings.loader.WordVectorSerializer;
import org.deeplearning4j.models.embeddings.wordvectors.WordVectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

@Component
public class VectorInterceptor implements HandlerInterceptor {

    private final ApplicationContext applicationContext;

    public VectorInterceptor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * 在拦截器中初始化 WordVectors 对象，并放在threadLocal中。WordVectors对象是线程安全的，可以在多个线程中共享。
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        WordVectors wordVectors =  WordVectorsThreadLocal.getWordVectors();
        if (wordVectors != null) {
            return true;
        }
        wordVectors = applicationContext.getBean("wordVectors", WordVectors.class);
        WordVectorsThreadLocal.setWordVectors(wordVectors);
        return true; // 继续处理请求
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清理 ThreadLocal，避免内存泄漏
        WordVectorsThreadLocal.remove();
    }
}